package com.luban.authserver.config;

import com.luban.authserver.config.customfilter.login.CustomAuthenticationManager;
import com.luban.authserver.config.enhancer.JwtTokenEnhancer;
import com.luban.authserver.config.tokengranter.SmsCodeTokenGranter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author Fox
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private CustomAuthenticationManager customAuthenticationManager;

    //    @Autowired
//    private DataSource dataSource;
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    @Qualifier("jwtTokenStore")
    private TokenStore tokenStore;
    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Autowired
    private JwtTokenEnhancer jwtTokenEnhancer;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Override
    // 客户端配置
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //password模式
        // http://localhost:8888/oauth/token?username=fox&password=123456&grant_type=password&client_id=gateway-server&client_secret=123123&scope=read

        // 用数据库维护客户端信息
        //clients.withClientDetails(clientDetails());

        // 授权码模式
        // 第一步 先根据client的clientId 和需要重定向的redirect_uri
        // http://localhost:8888/oauth/authorize?response_type=code&client_id=client&redirect_uri=http://localhost:8888/login
        // 第二步：授权，并拿到第一步返回的code
        // https://www.baidu.com/?code=9fv9aI
        // 第三步：根据返回的code 和 clientId 和 secret 去认证服务器获取token
        // http://localhost:8888/oauth/token?client_id=client&client_secret=123&grant_type=authorization_code&code=9fv9aI&redirect_uri=http://localhost:8888/login
        //  # client_id和client_secret用来让 B 确认 A 的身份,client_secret参数是保密的，因此只能在后端发请求
        //    #    AUTHORIZATION_CODE # 采用的授权方式是授权码


        // 内存模式
        clients.inMemory()
                //配置client_id
                .withClient("client")
                //配置client-secret
                .secret(passwordEncoder.encode("123"))
                //配置访问token的有效期
                .accessTokenValiditySeconds(3600)
                //配置刷新token的有效期
                .refreshTokenValiditySeconds(864000)
                //配置redirect_uri，用于授权成功后跳转
                .redirectUris("http://www.baidu.com")
                //配置申请的权限范围
                .scopes("all")
                /**
                 * 配置grant_type，表示授权类型
                 * authorization_code: 授权码
                 * password： 密码
                 * client_credentials: 客户端
                 * refresh_token: 更新令牌
                 * sms_code: 自定义短信登陆验证
                 */
                .authorizedGrantTypes("authorization_code", "password", "refresh_token","sms_code")
                .and()
                .withClient("client2")
                .secret(passwordEncoder.encode("456"))
                .accessTokenValiditySeconds(3600)
                .refreshTokenValiditySeconds(864000)
                .redirectUris("http://www.baidu.com")
                .scopes("all")
                .authorizedGrantTypes("authorization_code", "password", "refresh_token");

    }

//    @Bean
//    public ClientDetailsService clientDetails() {
//        //读取oauth_client_details表
//        return new JdbcClientDetailsService(dataSource);
//    }

    private TokenGranter tokenGranter(final AuthorizationServerEndpointsConfigurer endpoints) {

        // endpoints.getTokenGranter() 获取SpringSecurity OAuth2.0 现有的授权类型
        List<TokenGranter> granters =
                new ArrayList<TokenGranter>(Collections.singletonList(endpoints.getTokenGranter()));

        // 构建短信验证授权类型
        SmsCodeTokenGranter smsCodeTokenGranter =
                new SmsCodeTokenGranter(endpoints.getTokenServices(), endpoints.getClientDetailsService(),
                        endpoints.getOAuth2RequestFactory());
//        smsCodeTokenGranter.setAccountService(accountService);
        // 向集合中添加短信授权类型
        granters.add(smsCodeTokenGranter);
        // 返回所有类型
        return new CompositeTokenGranter(granters);
    }


    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // TokenGranter 多认证方式实现入口，eg 短信登陆，二维码登陆
        //配置JWT的内容增强器
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> delegates = new ArrayList<>();
        delegates.add(jwtTokenEnhancer);
        delegates.add(jwtAccessTokenConverter);
        enhancerChain.setTokenEnhancers(delegates);
        // 如果密码验证是自定义的 这里需要设置自定义的bean
        endpoints.authenticationManager(customAuthenticationManager) //使用密码模式需要配置
                .tokenStore(tokenStore)  //配置存储令牌策略
                .tokenGranter(tokenGranter(endpoints)) // 多认证方式 eg 短信登陆，二维码登陆
                .accessTokenConverter(jwtAccessTokenConverter)
                .tokenEnhancer(enhancerChain) //配置tokenEnhancer
                .reuseRefreshTokens(true)  //refresh_token是否重复使用
                .userDetailsService(userDetailsService) //刷新令牌授权包含对用户信息的检查
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST); //支持GET,POST请求


//        endpoints.authenticationManager(authenticationManager) //使用密码模式需要配置
//                .tokenStore(tokenStore()) //指定token存储到redis
//               // .tokenEnhancer() // 给token添加额外信息
//               // .accessTokenConverter()
//                .reuseRefreshTokens(false)  //refresh_token是否重复使用
//                .userDetailsService(userDetailsService) //刷新令牌授权包含对用户信息的检查
//                .allowedTokenEndpointRequestMethods(HttpMethod.GET,HttpMethod.POST); //支持GET,POST请求
    }


    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        //允许表单认证
        security.allowFormAuthenticationForClients()
                // 配置校验token需要带入clientId 和clientSecret配置
                .checkTokenAccess("isAuthenticated()");
    }
}
